<?php
namespace app\admin\controller;

use app\common\model\UsedDeal as UsedDealModel;
use app\common\controller\AdminBase;
use think\Db;

/**
 * 管理
 * Class Adminuseddeal
 * @package app\admin\controller
 */
class UsedDeal extends AdminBase
{
    protected $useddeal_model;

    protected function _initialize()
    {
        parent::_initialize();
        $this->useddeal_model = new UsedDealModel();
    }

    /**
     * 管理
     * @param string $keyword
     * @param int    $page
     * @return mixed
     */
    public function index($coding = '',$page = 1)
    {
        $map = [];
        
        if($coding){
            $map['coding'] = ['like',"%{$coding}%"];
        }

        $useddeal_list = $this->useddeal_model->where($map)->order('id DESC')->paginate(15, false, ['page' => $page]);

        return $this->fetch('index', ['useddeal_list' => $useddeal_list, 'coding' => $coding]);
    }

    /**
     * 添加
     * @return mixed
     */
    public function add($truck_id)
    {
        return $this->fetch('add',['truck_id' => $truck_id]);
    }

    /**
     * 保存
     */
    public function save($truck_id)
    {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            $validate_result = $this->validate($data, 'UsedDeal');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                Db('used_truck')->where('id',$truck_id)->setField('deal',1);
                $truck_find = Db('used_truck')->where('id',$truck_id)->find();
                $data['coding'] = $truck_find['coding'];
                $data['price'] = intval($truck_find['price']) - intval($truck_find['low_price']);
                if($truck_find['user_id']){
                    $data['sell'] = Db('user')->where('id',$truck_find['user_id'])->value('phone');
                }

                if ($this->useddeal_model->allowField(true)->save($data)) {
                    $this->success('保存成功');
                } else {
                    $this->error('保存失败');
                }
            }
        }
    }

    /**
     * 删除
     * @param $id
     */
    public function delete($id = '', $ids = [])
    {
        $id = $ids ? array_merge($ids) : $id;

        if ($id) {
            if ($this->useddeal_model->destroy($id)) {
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        } else {
            $this->error('请选择需要删除的内容');
        }
    }

    /**
     * 浏览
     * @param  $[id] [description]
     */
    public function reading($id)
    {
        $deal_coding = Db('used_deal')->where('id',$id)->value('coding');
        $truck_id = Db('used_truck')->where('coding',$deal_coding)->value('id');
        $this->redirect('./admin/UsedTruck/reading',['id' => $truck_id]);
    }


}